from flask import Flask,request,jsonify
from utils.config import myconfig
from flask_cors import CORS
import json
from utils.db import db1
app = Flask(__name__)
app.config.from_object(myconfig)
CORS(app)
def getdata():
    data = request.data
    if request.method=="post":
        data = json.loads(data)
    else:
        data = request.form
    return data
# 登陆
@app.route('/login')
def login():
    # name = request.args.get("name")
    # password = request.args.get("password")
    # sql = "select * from users where name='%s' and password='%s'"%(name,password)
    # res = db1.find(sql)
    # if res:
    #     roleid = res['role_id']
    #     rsql = "select r.id,r.name,rs.id as rid,rs.resource from roles as r left join role_resource as " \
    #            "rr on r.id = rr.role_id inner join resources as rs on rr.resource_id=rs.id where r.id=%d"%int(roleid)
    #     reslist = db1.find_all(rsql)
    #     return jsonify({"code":200,"msg":"登陆成功","username":res["name"],"userid":res["id"],"list":reslist})
    # else:
    #     return jsonify({"code":400,"msg":"登陆失败"})
    #

    name = request.args.get('name')
    password = request.args.get("password")
    sql = "select * from users where name='%s' and password='%s'"%(name,password)
    res = db1.find(sql)
    if res:
        roleid =res['role_id']
        rsql = "select r.id,r.name,rs.id as rid,rs.resource from roles as r left join role_resource as rr on r.id = rr.role_id inner join resources as rs on rr.resource_id=rs.id where r.id=%d"%int(roleid)
        reslist = db1.find_all(rsql)
        return jsonify({'code':200,"msg":"登陆成功","username":res['name'],"userid":res['id'],"list":reslist})
    else:
        return jsonify({'code':400,"msg":"登陆失败"})



# 添加小说表
@app.route('/novels',methods=["POST"])
def novels():
    data = getdata()
    print(data)
    sql = "insert into novels(novel,status,user_id) values('%s',0,%d)"%(data["novel"],int(data["userid"]))
    db1.update(sql)
    return jsonify({"code":200,"msg":"添加成功"})


#查看小说表 未审核的
@app.route('/approvel')
def approvel():
    sql = "select * from novels where status=0"
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})


# 审核
@app.route('/isagree',methods=['POST'])
def is_agree():
    data = getdata()
    if data['isagree'] == "ok":
        sql = "update novels set status=1 where id=%d"%(int(data['id']))
        db1.update(sql)
        nsql = "select * from novels where id=%d"%(int(data['id']))
        res = db1.find(nsql)
        scql = "select * from users where id=%d"%int(res['user_id'])
        scres = db1.find(scql)
        if scres['score']:
            score = scres['score'] + 2
            scsql1 = "update users set score=%d where id=%d"%(score,int(res['user_id']))
            db1.update(scsql1)
        else:
            scsql = "update users set score=2 where id=%d"%(int(res['user_id']))
            db1.update(scsql)

        msql = "select * from users where id=%d"%int(res['user_id'])
        mres = db1.find(msql)
        time = int(datetime.datetime.now().timestamp())
        sql2 = "insert into scores(score,user_id,stime,tscore) values(%d,%d,%d,%d)" % (2, int(res["user_id"]),time,mres["score"])
        db1.update(sql2)
    else:
        sql1 = "update novels set status=0 where id=%d"%(int(data['id']))
        db1.update(sql1)
    return jsonify({'code':200,'msg':"ok"})




# 获取商品表
@app.route('/getgoods')
def getgoods():
    sql = "select * from goods"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})

import datetime
# 兑换商品
@app.route('/cgoods',methods=['POST'])
def cgoods():
    data = getdata()
    slq = "select * from users where id=%d"%int(data['userid'])
    res = db1.find(slq)

    gsql = "select * from goods where id=%d"%int(data['goodsid'])
    gres = db1.find(gsql)

    score = res['score'] - gres['score']
    if score>=0:
        nsql = "update users set score=%d where id=%d"%(score,int(data['userid']))
        db1.update(nsql)
        time = int(datetime.datetime.now().timestamp())
        ssql = "insert into scores(score,user_id,stime,tscore) values (%d,%d,%d,%d)"%(-gres['score'],
    int(data['userid']),time,score)
        db1.update(ssql)
        return jsonify({'code':200,'msg':'兑换成功'})
    else:
        return jsonify({'code':103,'msg':'积分不足'})


# # echars图
@app.route('/show')
def show():
    id = request.args.get("userid")
    stime = datetime.datetime.strftime((datetime.datetime.now() - datetime.timedelta(days=7)), "%Y-%m-%d")
    etime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")
    sql = "select from_unixtime(stime,'%%Y-%%m-%%d') as stime,group_concat(score) as tscore from scores where user_id=%d  and from_unixtime(stime,'%%Y-%%m-%%d') between '%s' and '%s' group by from_unixtime(stime,'%%Y-%%m-%%d') order by from_unixtime(stime,'%%Y-%%m-%%d')" % (
        int(id), stime, etime)
    data = db1.find_all(sql)
    tlst = []
    dlst = []
    lst = []
    num = 7
    for i in range(num, 0, -1):
        x = datetime.datetime.strftime((datetime.datetime.now() - datetime.timedelta(days=i)), "%Y-%m-%d")
        lst.append(x)
    print(lst)
    for i in data:
        tlst.append(i["stime"])
        dlst.append(sum([int(j) for j in i["tscore"].split(",")]))
    for i in lst:
        if i not in tlst:
            dlst.insert(lst.index(i), 0)
    # print(dlst)
    return jsonify({"code":200,"tlst":lst,"dlst":dlst})










if __name__ == '__main__':
    app.run()
